package cn.tedu.lucky.draw.server.job.scheduler;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @EnableScheduling 该注解表示开启定时任务
 */
@EnableScheduling
@Component
public class ActivityScheduler {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job activityExpirationJob;

    @Autowired
    private JobExplorer jobExplorer;

    /**
     * 定时任务
     * 注解说明：
     * 每半小时执行一次任务
     * 秒（0）：在第0秒的时候执行任务
     * 分（0/30）：在每小时的0分和30分钟执行一次
     * 时（*）:每个小时
     * 日（*）:每天
     * 月（*）：每个月
     * 周 (?):代表无指定
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void runJob() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder(new JobParameters(), jobExplorer)
                .addLong("time", new Date().getTime())//记录当前操作时间
                //获取下一个JobParameters
                .getNextJobParameters(activityExpirationJob).toJobParameters();
        jobLauncher.run(activityExpirationJob, jobParameters);
    }
}
